package com.paishen.peiniwan;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.paishen.common.LibCommon;
import com.paishen.common.util.BaseUtil;
import com.paishen.common.util.SpfsUtil;
import com.paishen.peiniwan.database.User;
import com.paishen.peiniwan.database.UserDao;
import com.paishen.peiniwan.database.util.ModelConverter;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.ServiceInfo;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.peiniwan.frame.http.response.HttpRespUser;
import com.paishen.peiniwan.module.MainActivity;
import com.paishen.peiniwan.module.login.AmazingLRActivity;
import com.squareup.okhttp.Request;
import com.umeng.analytics.MobclickAgent;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;


public class LauncherActivity extends BaseActivity {
    @Override
    public void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isSupportTouchBack = false;

        LibCommon.init(getApplicationContext());

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancelAll();

        boolean isFirstUse = true;
        int lastSplashVersion = SpfsUtil.readInt(C.sp.SETTINGS_SPLASH_VERSION, -1);
        if (lastSplashVersion >= BaseUtil.getAppVersionCode()) {
            isFirstUse = false;
        }

        if (isFirstUse) {
            redirect(SplashActivity.class);
        } else {
            User appUser = App.i().getUser();
            if (appUser != null && appUser.getApp_auto_login() != null && !TextUtils.isEmpty(appUser.getPhone()) && !TextUtils.isEmpty(appUser.getPassword())) {
                redirect(!appUser.getApp_auto_login() ? AmazingLRActivity.class : MainActivity.class);
            } else {
                long currUserId = SpfsUtil.readLong(C.sp.CURRENT_LOGIN_USER_ID);
                if (currUserId > 0) {
                    UserDao userDao = App.i().getDaoSession(currUserId).getUserDao();
                    final User dbUser = userDao.queryBuilder().where(UserDao.Properties.Id.eq(currUserId)).unique();
                    App.i().setUser(dbUser);
                    if (dbUser != null && dbUser.getApp_auto_login() != null && dbUser.getApp_auto_login() && !TextUtils.isEmpty(dbUser.getPhone()) && !TextUtils.isEmpty(dbUser.getPassword())) {
                        ImageView view = new ImageView(this);
                        view.setScaleType(ImageView.ScaleType.FIT_XY);
                        Glide.with(LauncherActivity.this).load(R.mipmap.launcher).into(view);
                        setContentView(view);
                        view.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                requestAutoLogin(dbUser);
                            }
                        }, 2000);
                    } else {
                        redirect(AmazingLRActivity.class);
                    }
                } else {
                    redirect(AmazingLRActivity.class);
                }
            }
        }
    }

    private void redirect(Class<?> target) {
        Intent intent = new Intent(LauncherActivity.this, target);
        startActivity(intent);
        ActivityCollector.finishAllExcept(target);
    }

    private void requestAutoLogin(final User dbUser) {
        String platform = "paishen";
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(),
                    PackageManager.GET_META_DATA);
            platform = appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (PackageManager.NameNotFoundException ignored) {
        }

        PnwHttpManager.Token.getServer(TAG, BaseUtil.getAppVersionCode(), platform, new PnwOkCallbackAdapter<HttpRespData<ServiceInfo>>() {
                    @Override
                    public void onResponse(HttpRespData<com.paishen.peiniwan.frame.http.entity.ServiceInfo> response, boolean fresh) {
                        super.onResponse(response, fresh);
                        if (response.errcode == C.http.RESULT_SUCCESS) {

                            PnwHttpManager.setCurrServiceUrl(response.data.server);

                            String phone = dbUser.getPhone();
                            String password = dbUser.getPassword();
                            PnwHttpManager.User.login(TAG, phone, password, new PnwOkCallbackAdapter<HttpRespUser<com.paishen.peiniwan.frame.http.entity.User>>() {
                                        @Override
                                        public void onResponse(HttpRespUser<com.paishen.peiniwan.frame.http.entity.User> response, boolean fresh) {
                                            super.onResponse(response, fresh);
                                            if (response.errcode == C.http.RESULT_SUCCESS) {
                                                com.paishen.peiniwan.database.User u = ModelConverter.mergeOrReplace(dbUser, response.user);
                                                EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, u));
                                                App.i().setUser(u);

                                                // 更新位置信息
                                                App.i().locationAsync();

                                                MobclickAgent.onProfileSignIn(u.getPhone());

                                                redirect(MainActivity.class);
                                                overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_scale_exit);
                                            } else {
                                                redirect(AmazingLRActivity.class);
                                                overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_scale_exit);
                                            }
                                        }

                                        @Override
                                        public void onFailure(Request request, Exception e) {
                                            redirect(AmazingLRActivity.class);
                                            overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_scale_exit);
                                        }
                                    }
                            );
                        }
                    }

                    @Override
                    public void onFailure(Request request, Exception e) {
                        redirect(AmazingLRActivity.class);
                    }
                }
        );
    }
}